package com.fish.yssb.ui.page.activity.constPara;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.fish.yssb.Consts;
import com.fish.yssb.R;
import com.fish.yssb.api.retData;
import com.fish.yssb.api.setApi;
import com.fish.yssb.db.RealmDb;
import com.fish.yssb.db.bean.BaseInfoTable;
import com.fish.yssb.db.excel.CopyExcel;
import com.fish.yssb.ui.page.activity.base.BaseActivity;
import com.fish.yssb.ui.page.adapter.constParaAdapter;
import com.fish.yssb.ui.page.dialog.PublicNoticeDialog;
import com.fish.yssb.ui.page.util.TopToastUtil;
import com.hy.srv101.CmdDataCell;
import com.jaeger.library.StatusBarUtil;
import com.syd.oden.circleprogressdialog.core.CircleProgressDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.HashMap;


/**
 * A login screen that offers login via email/password.
 */
public class ConstParaActivity extends BaseActivity implements OnClickListener {
    private static final String TAG = ConstParaActivity.class.getSimpleName();

    LinearLayout tv_back;
    ImageView tv_set;
    TextView tv_toptitle,tv_save,tv_load,tv_updata;

    private RecyclerView recyclerView;
    private constParaAdapter adapter;
    private  PublicNoticeDialog noticeDialog;
    private RelativeLayout ll_para_1, ll_para_2, ll_para_3;
    private CircleProgressDialog circleProgressDialog;

    private  ArrayList<BaseInfoTable> arrayList;
    public static void start(Context context) {
        Intent intent = new Intent(context, ConstParaActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setTransparent(this);
        StatusBarUtil.setDarkMode(this);
        setContentView(R.layout.activity_const_para_list);
        initview();
        EventBus.getDefault().register( this );
        circleProgressDialog = new CircleProgressDialog(ConstParaActivity.this);
        circleProgressDialog.setText("命令执行中");
        int ret =  setApi.getInstance(this).r_const_para();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister( this );
    }




    //初始化视图
    @SuppressLint("WrongViewCast")
    private void initview() {
        //登录层、下拉层、其它登录方式层
        recyclerView = (RecyclerView) findViewById(R.id.recylerview);
        recyclerView.setHasFixedSize(true);

        tv_toptitle = findViewById(R.id.tv_toptitle);
        tv_toptitle.setText("定值参数");

        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
        recyclerView.setAdapter(adapter = new constParaAdapter());

        adapter.replaceAll(getData());

        tv_back = findViewById(R.id.tv_back);
        tv_set = findViewById(R.id.tv_set);
        tv_load = findViewById(R.id.tv_load);
        tv_save = findViewById(R.id.tv_save);
        tv_updata = findViewById(R.id.tv_updata);
        tv_set.setOnClickListener(this);
        tv_back.setOnClickListener(this);
        tv_save.setOnClickListener(this);
        tv_load.setOnClickListener(this);
        tv_updata.setOnClickListener(this);
        Animation rotate = AnimationUtils.loadAnimation(this, R.anim.rotate_anim);
        if (rotate != null) {
            tv_set.startAnimation(rotate);
        }  else {
            tv_set.setAnimation(rotate);
            tv_set.startAnimation(rotate);
        }

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                tv_set.clearAnimation();
            }
        }, 3000);
//        int ret =  setApi.getInstance(this).r_const_para();
    }

    @Subscribe
    public void onEvent(final retData result) {
        //接收以及处理数据
        runOnUiThread(new Runnable() {
            public void run() {
                int strType = result.getType();
                int ret = result.getRet();
                int status = result.getStatus();
                circleProgressDialog.dismiss();
                if(strType == Consts.cm_w_const_para)
                {

                    if(ret == Consts.cm_timeout) {
                        TopToastUtil.getInstance(ConstParaActivity.this, R.layout.showdialog).showShortToast("命令执行超时");
                    }
                    if(ret == Consts.cm_end) {
                        if (status == 1) {
                            TopToastUtil.getInstance(ConstParaActivity.this, R.layout.showdialog).showShortToast("命令执行成功");
                            ArrayList<BaseInfoTable> dataList = new ArrayList<BaseInfoTable>();
                            dataList = adapter.dataList;
                            for (int i = 0; i < dataList.size(); i++) {
                                if (!"".equalsIgnoreCase(dataList.get(i).getRealVal())) {
                                    dataList.get(i).setRealVal("");
                                }
                            }
                            RealmDb.getInstance().insertRealmObjects(dataList);
                            adapter.notifyDataSetChanged();
                        }else{
                            TopToastUtil.getInstance(ConstParaActivity.this, R.layout.showdialog).showShortToast("命令执行失败");
                        }
                    }
                }
                if(strType == Consts.cm_r_const_para)
                {
                    circleProgressDialog.dismiss();
                    if(ret == Consts.cm_timeout) {
                        TopToastUtil.getInstance(ConstParaActivity.this, R.layout.showdialog).showShortToast("命令执行超时");
                    }

                    if(ret == Consts.cm_end) {
                        if(status == 1) {

                            if(result.getType()==Consts.cm_r_const_para)
                            {
//                                insertData("cm_r_const_para有返回值了");
                                ArrayList<CmdDataCell> list =   result.list;
                                if(list == null)
                                {
//                                    insertData("返回list为null");
                                    TopToastUtil.getInstance(ConstParaActivity.this, R.layout.showdialog).showShortToast("命令执行失败:返回list为null");
                                    return;
                                }
                                if(list.size() == 0)
                                {
//                                    insertData("返回list为0");
                                    TopToastUtil.getInstance(ConstParaActivity.this, R.layout.showdialog).showShortToast("命令执行失败:返回list为0");
                                    return;
                                }
//                                insertData("list数量："+list.size());
                                HashMap map = new HashMap();
                                for(int i=0;i<list.size();i++)
                                {
                                    CmdDataCell cell = list.get(i);

                                    short chanID = cell.GetChanID();

                                    String str = "0x"+ byteToHex(chanID);

//                                    byte [] aa = {0x03,0x00};
                                    byte [] aa = cell.GetDataBuf();
                                    String val = byteToInt(aa);
                                    map.put(str,val);
//                                    byte[] btyes = {0x58,0x00};



//                                    String str =  bytesToHexString(btyes);

                                }

                                for(int i=0;i<arrayList.size();i++)
                                {

                                     String  strVal =  (String) map.get( arrayList.get(i).getConnAdr());
                                    arrayList.get(i).setDefualtVal(strVal);

                                }
                                adapter.replaceAll(arrayList);
                                adapter.notifyDataSetChanged();
                            }

//                            TopToastUtil.getInstance(ConstParaActivity.this, R.layout.showdialog).showShortToast("命令执行成功");
                        }else{
                            TopToastUtil.getInstance(ConstParaActivity.this, R.layout.showdialog).showShortToast("命令执行失败");
                        }
                    }
                }
            }
        });
    };


    private final static String[] hexArray = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};

    public String byteToInt(byte[] bytes)
    {
        String str = "";
        int num = 0;
        switch (bytes.length)
        {
            case 1:
                 num = bytes[0] & 0xFF;
                break;
            case 2:
                 num = bytes[0] & 0xFF |(bytes[1] & 0xFF) << 8 ;
                break;
            case 3:
                num = bytes[0] & 0xFF |(bytes[1] & 0xFF) << 8 |(bytes[2] & 0xFF) << 16;
                break;
                case 4:
                    num = bytes[0] & 0xFF |(bytes[1] & 0xFF) << 8  |(bytes[2] & 0xFF) << 16 |(bytes[3] & 0xFF) << 24;
            break;
        }

        str = num+"";
        return str;
    }
    public String byteToHex(int n) {

        if(n>65535)
        {
            n = n-65535;
        }

        int m = n/256;
        int m1= n%256;


        int d1 = m/16;
        int d2 = m%16;
        int d3 = m1 / 16;
        int d4 = m1 % 16;
        return hexArray[d3] + hexArray[d4]+hexArray[d1] + hexArray[d2];
    }


    @Override
    public void onClick(View view) {


        switch (view.getId()) {

            case R.id.tv_updata:

                noticeDialog = new PublicNoticeDialog(ConstParaActivity.this, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        String sendStatus = "";
                        if (view.getId() == R.id.btn_chancel_notice) {//暂存

                            noticeDialog.dismiss();
                        } else {//生成
//                             ArrayList<BaseInfoTable> dataList = new ArrayList<BaseInfoTable>();
//                            ArrayList<BaseInfoTable> sendList = new ArrayList<BaseInfoTable>();
//                             dataList = adapter.dataList;
//                             for(int i=0;i<dataList.size();i++)
//                             {
//                                 if(!"".equalsIgnoreCase(dataList.get(i).getRealVal())) {
////                                                     dataList.get(i).setDefualtVal(dataList.get(i).getRealVal());
//                                     dataList.get(i).setRealVal("");
//                                     sendList.add( dataList.get(i));
//                                 }
//                             }
//                             RealmDb.getInstance().insertRealmObjects(dataList);
//                             adapter.notifyDataSetChanged();
//                            noticeDialog.dismiss();
                            circleProgressDialog.showDialog();
                            ArrayList<BaseInfoTable> dataList = new ArrayList<BaseInfoTable>();
                            ArrayList<BaseInfoTable> sendList = new ArrayList<BaseInfoTable>();
                            dataList = adapter.dataList;
                            for(int i=0;i<dataList.size();i++)
                            {
                                if(dataList.get(i).getRealVal()!=null && !"".equalsIgnoreCase(dataList.get(i).getRealVal())) {
                                    sendList.add( dataList.get(i));
                                }
                            }
//                            RealmDb.getInstance().insertRealmObjects(dataList);
//                             adapter.notifyDataSetChanged();
//                            noticeDialog.dismiss();
                            setApi.setConstPara(sendList);

                        }
                        noticeDialog.dismiss();

                    }
                }, 1, "", "确认下装参数？", "取消", "确定");
                noticeDialog.show();


                break;
            case R.id.tv_back:
                finish();
                break;
            case R.id.tv_set:
                int ret =  setApi.getInstance(this).r_const_para();
                Animation rotate = AnimationUtils.loadAnimation(this, R.anim.rotate_anim);
                if (rotate != null) {
                    tv_set.startAnimation(rotate);
                }  else {
                    tv_set.setAnimation(rotate);
                    tv_set.startAnimation(rotate);
                }

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        tv_set.clearAnimation();
                    }
            }, 3000);


                break;
            case R.id.tv_load:
//                int ret =  setApi.getInstance(this).r_const_para();
//                setCmdRet(ret,"定值参数读取");
                CopyExcel excel1 = new CopyExcel();
                HashMap<String ,BaseInfoTable>  list = excel1.readData(ConstParaActivity.this);
                ArrayList<BaseInfoTable> dataList_tmp = new ArrayList<BaseInfoTable>();
                dataList_tmp = getData();
                if(list!=null && list.size()>0)
                {

                    for(int i=0;i<dataList_tmp.size();i++)
                    {
                        BaseInfoTable info = dataList_tmp.get(i);
                        if(list.containsKey(info.getConnAdr()))
                        {

                            BaseInfoTable infotmp = list.get(info.getConnAdr());
                            if(infotmp!=null)
                            {
                                info.setRealVal(infotmp.getRealVal());
                            }
                        }
                    }
                    adapter.replaceAll(dataList_tmp);
                    adapter.notifyDataSetChanged();
                }


                TopToastUtil.getInstance(this,R.layout.showdialog).showShortToast("加载成功");
                break;
            case R.id.tv_save:
                    ArrayList<BaseInfoTable> dataList = new ArrayList<BaseInfoTable>();
                                                                dataList = adapter.dataList;



                RealmDb.getInstance().insertRealmObjects(dataList);
                                                                adapter.notifyDataSetChanged();
                CopyExcel excel = new CopyExcel();
                excel.writeData(dataList);
                TopToastUtil.getInstance(this,R.layout.showdialog).showShortToast("保存成功");
                break;
            default:
                break;
        }


    }

    public ArrayList<BaseInfoTable> getData()
    {
//        List<BaseInfoTable> list = (List<BaseInfoTable>) RealmDb.getInstance().queryRealmObjects(BaseInfoTable.class);

//        Log.e("=========","count:"+list.size());
         arrayList = (ArrayList) RealmDb
                .getInstance()
                .queryRealmObjectsByData(BaseInfoTable.class,"paraType",5);

        return arrayList;
    }

}

